package com.qfedu.edu.interceptor;

import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.result.R;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.slot.base.SlotChain;
import com.qfedu.edu.slot.generate.GenerateSlot;
import com.qfedu.edu.utils.HttpResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截器
 */
@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    @Autowired
    private SlotChain slotChain;

    // 在请求处理之前进行调用（Controller方法调用之前）
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("执行到了全局的拦截器中....");
        try {
            slotChain.dealReq(request);//这里不会返回false，所以可以直接返回true
            log.info("slot执行通过");
            return true;
        } catch (Exception e) {
           //抛出异常，则说明请求处理的slot出现了问题
            //根据异常类型，做相应的处理
            //通知前端执行slot出现问题
            if (e instanceof BusinessException){
                //抛出可预期的异常，则说明请求处理的slot出现了问题
                BusinessException businessException = (BusinessException) e;
                R error = R.error(businessException.getCode(), businessException.getMessage());
                HttpResponseUtils.sendResponse(response,error);
            }else {
                //说明抛出的是未知异常
                R error = R.error(ResponseCode.SLOT_INVOKE_EXCEPTION);
                HttpResponseUtils.sendResponse(response,error);
            }
        }
        log.info("slot执行未通过");
        return false;
    }
}
